import socket
import threading
import os
import time


class HTTPWebServer(object):

    def __init__(self, port):
        self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server.bind(("", port))
        self.server.listen(128)

    @classmethod
    def handle_client_req(cls, client):
        print("handle_client_req")
        data = client.recv(4096)
        if not data:
            client.close()
            print("客户端断开连接")
            return
        res_path = data.decode("utf-8").split(maxsplit=2)
        full_path = "static" + res_path[1]
        print(full_path)
        with open(full_path, "rb") as file:
            content = file.read()
        response_line = "HTTP/1.0 200 OK\r\n"
        response_header = "Server: KTM\r\nContent-Type: text/html; charset=UTF-8\r\n"
        response_body = content
        response_data = (response_line + response_header + "\r\n").encode("UTF-8") + response_body
        client.send(response_data)
        client.close() # ？？？

    def start(self):
        while True:
            client, ip_port = self.server.accept()
            t = threading.Thread(target=self.handle_client_req, args=(client,))
            t.setDaemon(True)
            t.start()


if __name__ == '__main__':
    http_server = HTTPWebServer(8000)
    http_server.start()

